<template>
    <div class="materialMgt-index yuan-container">
        <a-card title="检验检测">
            <div style="margin-bottom: 10px;">
                <a-alert :message="alert" type="info" close-text="关闭" />
            </div>
            <div style="margin-bottom: 10px; display: flex; justify-content: flex-end; align-items: center;">
                <a-button type="primary" style="margin-right: 8px" @click="handleDownloadTemplate">下载导入模板</a-button>
                <a-button type="primary" style="margin-right: 8px" @click="handleExport">导出</a-button>
                <a-upload
                    :showUploadList="false"
                    :beforeUpload="handleImport"
                    accept=".xls,.xlsx"
                >
                    <a-button type="primary">导入</a-button>
                </a-upload>
            </div>
            <a-tabs type="card" :default-active-key="rawTypeKey" @change="tabChange">
                <a-tab-pane v-for="(item, i) in tabsData" :key="item" :tab="item"></a-tab-pane>
            </a-tabs>
            <div class="table">
                <a-table bordered :rowKey="item=>item.id" :data-source="pageList" :columns="columns" :pagination="pagination" :loading="loading"></a-table>
            </div>
        </a-card>

        <check-or-detail :viewDetail="viewDetail" :data="data" :rowKey="rawTypeKey" :visible="addVisible" @closeModal="closeModal"/>

    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { h } from "vue";
import nextApi from "@/api/nextApi";
import CheckOrDetail from "@/views/inspectionView/components/checkOrDetail.vue";
import { downLoadFile } from "@/utils";

@Component({
    name: "materialMgtMgtIndex",
    components: {CheckOrDetail},
})
export default class extends Vue {
    tabsData = ['饮片检测','提取物检测','颗粒检测','成品检测'];
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    columns = [
        {
            title:'序号',
            dataIndex:'index',
            key:'index',
            align:'center',
            customRender:(text,record,index:number)=>index+1
        },
        {
            title: '批号',
            dataIndex: "batch",
            key: "batch",
            align: "center",
        },
        {
            align: "center",
            dataIndex: "materialName",
            key: "materialName",
            title: "品名",
        },
        {
            align: "center",
            dataIndex: "standard",
            key: "standard",
            title: "标准"
        },
        {
            align: "center",
            dataIndex: "availableSellDay",
            key: "availableSellDay",
            title: "可销售天数",
            customRender:(text)=>text+'天'
        },
        {
            align: "center",
            dataIndex: "reportDate",
            key: "reportDate",
            title: "报告日期",
        },
        {
            align: "center",
            dataIndex: "state",
            key: "state",
            title: "检验状态",
            customRender: (text: string, record: any, index: number) => {
                const stateBox = h(
                    "div",
                    { class: record.state === "1" ? "c-danger" :  record.state === "2" ? '.c-warning':'c-success' },
                    record.state === "1" ? '待检验':record.state === "2" ? '检验中':'已完(已出报告)'
                );
                return stateBox;
            },
        },
        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width: 260,
            customRender: (text: any, record: any) => {
                const editBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.check(record) },
                    },
                    "检验"
                );
                const detailBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "10px" },
                        props: { icon: "eye", type: "primary", size: "small" },
                        on: { click: () => this.showDetail(record) },
                    },
                    "查看"
                );

                const btn: any[] = [];
                btn.push(editBtn);
                btn.push(detailBtn);
                return h("div", btn);
            },
        },

    ];
    loading = false;
    pageList: any[] = [];
    keywords = "";
    rawTypeKey = "饮片检测";
    alert = '请先在生产日报表-前处理环节添加饮片数据'
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getList({
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                type: this.rawTypeKey,
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.records || [];
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    tabChange(e: string) {
        this.rawTypeKey = e;
        // tab 对应的提示内容
        const alertMap: Record<string, string> = {
            '饮片检测': '请先在生产日报表-前处理环节添加饮片数据',
            '提取物检测': '请先在生产日报表-提取环节添加提取物数据',
            '颗粒检测': '请先在生产日报表-制粒环节添加颗粒数据',
            '成品检测': '请先在生产日报表-包装环节添加成品数据',
        };
        this.alert = alertMap[e] || '';
        // 更新批号列的显示
        const batchNumberColumn = this.columns.find(col => col.dataIndex === 'batchNumber');
        if (batchNumberColumn) {
            batchNumberColumn.title = `${e.slice(0,2)}批号`;
        }
        if(this.rawTypeKey == '成品检测'){
            //表头配置插入
            this.columns.splice(3,0,{
                align: "center",
                dataIndex: "inventoryType",
                key: "inventoryType",
                title: "产品大类",
            })
        }else if(this.columns[3].title == '产品大类'){
            this.columns.splice(3,1)
        }
        this.resetList();
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    async mounted() {
        this.getList();
    }
    viewDetail = false;
    showDetail(item: any) {
        this.data = item;
        this.addVisible = true;
        this.viewDetail = true;
    }

    data = {};
    addVisible = false;
    check(item: any) {
        this.data = item;
        this.addVisible = true;
    }
    closeModal(){
        this.addVisible = false;
        this.viewDetail = false;
        this.data = {};
        this.getList();
    }
    //导入模板
    handleDownloadTemplate() {
        nextApi.downloadTemplate((res: any) => {
            const blob = new Blob([res.data],{
                type: "application/vnd.ms-excel",
            })
            downLoadFile(blob, this.rawTypeKey + "_导入模板");
        });
    }
    handleExport() {
        nextApi.exportCheckResult({type:this.rawTypeKey},(res:any)=>{
            const blob = new Blob([res.data], {
                // type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                type: "application/vnd.ms-excel",
            });
            downLoadFile(blob,this.rawTypeKey);
        })
    }
    handleImport(file: File) {
        let formData = new FormData();
        formData.append("file", file);
        formData.append("type", this.rawTypeKey);
        this.upload(formData);
        return false;
    }
    async upload(formData:any){
        try {
            const res = await nextApi.importCheckResult(formData);
            console.log(res)
            this.$message.success(res.msg);
            await this.getList()
        } finally {

        }
    }
}
</script>
<style scoped lang="scss">
.materialMgt-index {
    padding: 20px;
}
</style>
